var stompClient = null;
//此值有服务端传递给前端,实现方式没有要求
var count = 0;


function setConnected(connected) {
    document.getElementById('connect').disabled = connected;
    document.getElementById('disconnect').disabled = !connected;
    document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
    $('#response').html();
}

function connect() {
    var userId = $("#currentuid").val();
    var socket = new SockJS('/endpointWisely'); //1连接SockJS的endpoint是“endpointWisely”，与后台代码中注册的endpoint要一样。
    stompClient = Stomp.over(socket);//2创建STOMP协议的webSocke6t客户端。
    stompClient.connect({}, function (frame) {//3连接webSocket的服务端。
        // setConnected(true);
        //通过stompClient.subscribe（）订阅服务器的目标是'/user/' + userId + '/msg'接收一对一的推送消息,其中userId由服务端传递过来,用于表示唯一的用户,通过此值将消息精确推送给一个用户
        stompClient.subscribe('/user/' + userId + '/msg', function (respnose) {
            console.log("----------解析来自员工的信息----connect---------");
            console.log(respnose);
            count++;
            showResponse1(JSON.parse(respnose.body),count);
        });
    });
}


function disconnect() {
    if (stompClient != null) {
        stompClient.disconnect();
    }
    setConnected(false);
    console.log("Disconnected");
}

/***
 *
 * @param toid 接收人id
 * @param msg 发送的消息
 */
function sendEmp(toid,msg) {
    var userId = $("#currentuid").val();
    //通过stompClient.send（）向地址为"/welcome"的服务器地址发起请求，与@MessageMapping里的地址对应。因为我们配置了registry.setApplicationDestinationPrefixes(Constant.WEBSOCKETPATHPERFIX);所以需要增加前缀/ws-push/
    stompClient.send("/ws-push/emp", {}, JSON.stringify({'from': userId,'to':toid,'content':msg}));
}




function showResponse1(message,count) {
    console.log("------------showResponse1----------------");
    // console.log(typeof message);
    console.log(message);
    // var res = JSON.parse(message);
    var response = $("#callMsg");
    var player = $("#myAudio")[0];
    setTimeout('',1000);
    player.play();
    var msgCount =$("#msgCount");
    msgCount.html(count);
    response.prepend('<li class="tpl-dropdown-menu-messages">' +
        ' <div class="menu-messages-content">' +
        ' <div class="menu-messages-content-title">' +
        ' <i class="am-icon-circle-o am-text-success">' + message.from+':'+new Date(message.time).toLocaleString()+'</i>'+
         '</div> <div class="am-text-truncate">' +
            message.content
         +'</div></div></li>');
}

/**
 * 根据岗位获取当前在线的对应员工，只能显示本店的员工
 * @param typeName
 */
function getOnlineEmp(obj,typeName){
    var jumpUrl =obj.getAttribute("data-url");
    var illNo =obj.getAttribute("data-no");
    var formData = new FormData();
    formData.append("type",typeName);
    $.ajax({
        url: '/getallemp',
        type: "POST",
        data:formData,
        cache: false,
        async: false,
        processData: false,
        contentType: false
    }).done(function (res) {
        console.log(res);
        if (res.emp != null && res.emp !=undefined && res.emp !=''){
            var $select = $('#push-chosen');
            $select.empty();
            var selectsTR ='<option ></option>';
            for (var i=0;i<res.emp.length;i++){
                selectsTR +='<option value="'+res.emp[i].emId+'">'+ res.emp[i].emName +'</option>';
            }
            $select.append(selectsTR);
            $select.trigger('chosen:updated');
            $('#my-push-model').modal({
                relatedTarget: this,
                onConfirm: function(e) {
                    var data = $select.val();
                    console.log(data);
                    var msg ='<a href="'+jumpUrl+'" target="_blank">编号：'+illNo+'需要处理</a>';
                    sendEmp(data,msg);
                },
                onCancel: function(e) {
                    // alert('不想说!');
                    $select.empty();
                }
            });
        }else {
            alert("当前没有员工在线！")
        }
    });
}